package com.tenglong.teacher.ui.publish;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.MyFragmentPagerAdapter;
import com.cuotibao.zhuoxiao.basics.utils.DensityUtil;
import com.cuotibao.zhuoxiao.basics.utils.ScreenUtil;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.netease.nimlib.sdk.msg.attachment.FileAttachment;
import com.netease.nimlib.sdk.msg.attachment.ImageAttachment;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.requestInfo.CorrectInfo;
import com.tenglong.teacher.data.requestInfo.HomeworkCorrectInfo;
import com.tenglong.teacher.data.resultInfo.HomeWorkIM;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.common.activity.BaseActivity;
import com.tenglong.teacher.ui.common.view.NoScrollViewPager;
import com.tenglong.teacher.ui.dialog.ExitDialog;
import com.tenglong.teacher.ui.dialog.HomeworkErrorsFragment;
import com.tenglong.teacher.ui.publish.text.DoodleOnTouchGestureListener;
import com.tenglong.teacher.ui.publish.text.DoodleStoreText;
import com.tenglong.teacher.ui.publish.text.MyDoodleText;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hzw.doodle.DoodleBitmap;
import cn.hzw.doodle.DoodleColor;
import cn.hzw.doodle.DoodlePen;
import cn.hzw.doodle.DoodleSelectableItemBase;
import cn.hzw.doodle.DoodleShape;
import cn.hzw.doodle.DoodleView;
import cn.hzw.doodle.core.IDoodleItem;
import cn.hzw.doodle.core.IDoodlePen;
import cn.hzw.doodle.core.IDoodleSelectableItem;
import cn.hzw.doodle.dialog.DialogController;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class HomeworkCorrectingActivity extends BaseActivity implements HomeworkActiviCallback, ViewPager.OnPageChangeListener, HomeworkErrorsFragment.HomeworkErrorsDialogListener {

    public static final String KEY_SESSION_ID = "key_session_id";

    public static final String KEY_ACCOUNT_ID = "key_account_id";

    public static final String KEY_HOME_IM_PARAMS = "key_homework_im_params";

    /**
     * 滑动控件
     */
    private NoScrollViewPager mViewPager;

    /**
     * 底部工作栏控件
     */
    private ViewGroup mBottomLayout;

    /**
     * 用于区分当前属于那种操作
     */
    private SelectType selectType = SelectType.CORRECT;

    /**
     * 用于旋转图片的动画
     */
    private ValueAnimator mRotateAnimator;

    /**
     * 涂鸦控件
     */
    private DoodleView mDoodleView;

    /**
     * 与涂鸦控件配合的手势监听器
     */
    private DoodleOnTouchGestureListener mTouchGestureListener;

    /**
     * viewPager当前位置
     */
    private int currentPosition = 0;

    /**
     * 展示viewPage页数的控件
     */
    private TextView pagerNumber;

    /**
     * 及时通讯消息
     */
    private List<IMMessage> imMessages;

    /**
     * 图片显示区域宽度
     */
    private int imageAreaWidth = 0;

    /**
     * 图片显示区域高度
     */
    private int imageAreaHeight = 0;

    /**
     * word文档名字数组
     */
    private ArrayList<String> errerTypeInfos;

    /**
     * 图片错题数组
     */
    private List<HomeworkCorrectInfo> homeworkCorrectInfos;

    /**
     * 错题IDoodleItem数组
     */
    private Map<Integer, ArrayList<IDoodleItem>> wrongNumberItems = new HashMap<>();

    /**
     * 切换按钮
     */
    private TextView switchImage;

    /**
     * 清屏控件
     */
    private View cls;

    /**
     * 上一页控件
     */
    private TextView previousPage;

    /**
     * 下一页控件
     */
    private TextView nextPage;

    private String sessionId;

    private String accountId;

    private String tag;
    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_homework_correcting);
        findViewById(R.id.actionbar_container).setVisibility(View.GONE);
        if (imMessages == null || imMessages.size() == 0) {
            imMessages = (List<IMMessage>) getIntent().getSerializableExtra(KEY_HOME_IM_PARAMS);
        }
        if (imMessages == null || imMessages.size() == 0) {
            this.finish();
            return;
        }
        tag=getIntent().getStringExtra("tag");
        sessionId = getIntent().getStringExtra(KEY_SESSION_ID);
        if (TextUtils.isEmpty(sessionId)) {
            ToastUtils.showCenterToast("缺少sessionId参数");
            finish();
            return;
        }
        accountId = getIntent().getStringExtra(KEY_ACCOUNT_ID);
        if (TextUtils.isEmpty(accountId)) {
            ToastUtils.showCenterToast("缺少accountId参数");
            finish();
            return;
        }
        if (homeworkCorrectInfos == null) {
            homeworkCorrectInfos = new ArrayList<>();
        }
        for (int i = 0; i < imMessages.size(); i++) {
            HomeworkCorrectInfo info = new HomeworkCorrectInfo();
            String url = ((ImageAttachment) imMessages.get(i).getAttachment()).getUrl();
            if ((!TextUtils.isEmpty(url)) && url.contains("/")) {
                String[] saa = url.split("/");
                info.filename = saa[(saa.length - 1)];
            } else {
                info.filename = url == null ? "" : url;
            }
            info.currentUrl = getImageUrl(imMessages.get(i), info);
            info.sessionId = sessionId;
            info.studentAccId = accountId;
            info.position = i;
            info.imMsgId = ((HomeWorkIM) imMessages.get(i)).getId();
            homeworkCorrectInfos.add(info);
            wrongNumberItems.put(i, new ArrayList<IDoodleItem>());
        }
        initView();
        setAdapter();
        setListeners();
        initViewState();
    }

    /**
     * 初始化链接
     *
     * @param imMessage
     * @param info
     * @return
     */
    public String getImageUrl(IMMessage imMessage, HomeworkCorrectInfo info) {
        FileAttachment msgAttachment = (FileAttachment) imMessage.getAttachment();
        String thumbPath = msgAttachment.getThumbPath();
        String url = msgAttachment.getUrl();
        if (url.contains("_thumbnailwh")) {
            info.isOriginalImage = false;
            info.compressUrl = url;
            if (url.contains(".png") && url.split(".png").length >= 2) {
                info.originalUrl = url.split("_thumbnailwh")[0];
            } else {
                if (!TextUtils.isEmpty(thumbPath)) {
                    info.originalUrl = thumbPath;
                } else {
                    info.originalUrl = "";
                }
            }
            return info.compressUrl;
        } else {
            info.isOriginalImage = true;
            if (!TextUtils.isEmpty(url)) {
                return url;
            } else if (!TextUtils.isEmpty(thumbPath)) {
                return thumbPath;
            } else {
                return "";
            }
        }
    }

    /**
     * 初始化view
     */
    private void initView() {
        mViewPager = findViewById(R.id.mViewPager);
        mBottomLayout = findViewById(R.id.bottomLayout);
        pagerNumber = findViewById(R.id.pagerNumber);
        switchImage = findViewById(R.id.switchImage);
        cls = findViewById(R.id.cls);
        previousPage = findViewById(R.id.previousPage);
        nextPage = findViewById(R.id.nextPage);
    }

    /**
     * 设置adapter
     */
    private void setAdapter() {
        if (homeworkCorrectInfos == null || mViewPager == null) return;
        MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
        for (int i = 0; i < homeworkCorrectInfos.size(); i++) {
            adapter.addFragment(getFragment(getSupportFragmentManager(), i));
        }
        mViewPager.setAdapter(adapter);
        mViewPager.setOffscreenPageLimit(homeworkCorrectInfos.size() - 1);
    }

    /**
     * view设置监听
     */
    private void setListeners() {
        for (int i = 0; i < mBottomLayout.getChildCount(); i++) {
            mBottomLayout.getChildAt(i).setOnClickListener(this);
        }
        mViewPager.addOnPageChangeListener(this);
        switchImage.setOnClickListener(this);
        cls.setOnClickListener(this);
        previousPage.setOnClickListener(this);
        nextPage.setOnClickListener(this);
    }

    /**
     * 初始化界面
     */
    @SuppressLint("SetTextI18n")
    private void initViewState() {
        findViewById(R.id.save).setVisibility(homeworkCorrectInfos.size() == 1 ? View.VISIBLE : View.GONE);
        pagerNumber.setText(1 + "/" + homeworkCorrectInfos.size());
        switchImage.setVisibility(homeworkCorrectInfos.get(currentPosition).isOriginalImage ? View.GONE :
                (TextUtils.isEmpty(homeworkCorrectInfos.get(currentPosition).originalUrl) ? View.GONE : View.VISIBLE));
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.painting:
                initSetViewSelect(v, DoodlePen.BRUSH, SelectType.REDACT, false, true);
                break;
            case R.id.checkNumber:
                initSetViewSelect(v, DoodlePen.BITMAP, SelectType.CORRECT, false, false);
                break;
            case R.id.wrongNumber:
                initSetViewSelect(v, DoodlePen.BITMAP, SelectType.ERROR, false, false);
                break;
            case R.id.voice:
                initSetViewSelect(v, DoodlePen.TEXT, SelectType.TEXT, false, false);
                break;
            case R.id.delete:
                initSetViewSelect(v, null, SelectType.DELETE, true, false);
                break;
            case R.id.rotate:
                imageRotate();
                break;
            case R.id.save:
                if (isUpLoad()) {
                    skipWorkPaper();
                    return;
                }
                imageSave();
                break;
            case R.id.back:
                onBackPressed();
                break;
            case R.id.switchImage:
                if (homeworkCorrectInfos == null) return;
                HomeworkCorrectInfo erre = homeworkCorrectInfos.get(currentPosition);
                if (erre != null) {
                    if (!erre.isOriginalImage) {
                        switchBitmap();
                    }
                }
                break;
            case R.id.cls:
                if (isFinishing()) return;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    if (isDestroyed()) return;
                }
                if (!setSelectedItemState(false) && homeworkCorrectInfos == null) {
                    return;
                }
                ExitDialog.getExitDialog("确定清屏?").setExitListener(new ExitDialog.ExitListener() {
                    @Override
                    public void onExit(boolean exitState) {
                        if (exitState) {
                            mDoodleView.clear();
                            HomeworkCorrectInfo info = homeworkCorrectInfos.get(currentPosition);
                            info.errors.clear();
                            info.errorNum = 0;
                            setSelectedItemState();
                            setClearGreenViewState();
                        }
                    }
                }).show(getSupportFragmentManager(), "clearScreenDialog");
                break;
            case R.id.nextPage:
                if (mViewPager != null && homeworkCorrectInfos != null) {
                    mViewPager.setCurrentItem(currentPosition + 1);
                }
                break;
            case R.id.previousPage:
                if (mViewPager != null && homeworkCorrectInfos != null) {
                    mViewPager.setCurrentItem(currentPosition - 1);
                }
                break;
        }
    }

    /**
     * 切换原图前预备判断
     */
    private void switchBitmap() {
        if (!setSelectedItemState(false)) {
            return;
        }
        List<IDoodleItem> allItem = mDoodleView.getAllItem();
        if (allItem != null && allItem.size() > 0) {
            switchBitmapTipDialog();
        } else {
            changeOriginalImageState();
        }
    }

    /**
     * 压缩的作业已经批改，切换原图是提示
     */
    private void switchBitmapTipDialog() {
        if (isFinishing()) return;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (isDestroyed()) return;
        }
        ExitDialog.getExitDialog("切换原图，此张作业批改数据将消失。").setExitListener(new ExitDialog.ExitListener() {
            @Override
            public void onExit(boolean exitState) {
                if (exitState) {
                    changeOriginalImageState();
                }
            }
        }).show(getSupportFragmentManager(), "switchBitmapTipDialog");
    }

    /**
     * 切换原图，具体操作
     */
    private void changeOriginalImageState() {
        if (homeworkCorrectInfos == null) return;
        HomeworkCorrectInfo errorInfo = homeworkCorrectInfos.get(currentPosition);
        if (errorInfo != null) {
            errorInfo.isOriginalImage = true;
            errorInfo.currentUrl = errorInfo.originalUrl;
            HomeworkCorrectingFragment f = getFragment(getSupportFragmentManager(), currentPosition);
            if (f != null) {
                f.refreshBitmap();
                switchImage.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 批改后上传服务器
     */
    private void imageSave() {
        if (!setSelectedItemState(false)) {
            return;
        }
        if (homeworkCorrectInfos == null || mViewPager == null) return;
        mViewPager.setNoScroll(false);
        if (isDrawReady()) {
            List<Integer> itemPositions = getNoScrawlPosition();
            if (itemPositions.size() == 0) {
                showProgressDialog("数据初始化中...");
                toSave();
            } else {
                if (homeworkCorrectInfos == null) return;
                if (itemPositions.size() == homeworkCorrectInfos.size()) {
                    ToastUtils.showCenterToast("还没有批改作业");
                    return;
                }
                StringBuffer text = new StringBuffer();
                text.append("第");
                for (int i = 0; i < itemPositions.size(); i++) {
                    Integer item = itemPositions.get(i);
                    text.append((i == itemPositions.size() - 1) ? item + "" : item + "、");
                }
                text.append("页未批改");
                ToastUtils.showCenterToast(text.toString());
            }
        } else {
            ToastUtils.showCenterToast("图片未全部加载");
        }
    }

    /**
     * 旋转图片
     */
    private void imageRotate() {
        if (!setSelectedItemState(false)) {
            return;
        }
        // 旋转图片
        if (mRotateAnimator == null) {
            mRotateAnimator = new ValueAnimator();
            mRotateAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    int value = (int) animation.getAnimatedValue();
                    mDoodleView.setDoodleRotation(value);
                }
            });
            mRotateAnimator.setDuration(250);
        }
        if (mRotateAnimator.isRunning()) {
            return;
        }
        mRotateAnimator.setIntValues(mDoodleView.getDoodleRotation(), mDoodleView.getDoodleRotation() + 90);
        mRotateAnimator.start();
        mViewPager.setNoScroll(false);
    }

    @Override
    public void onBackPressed() {
        if (!taskisDauber()) {
            super.onBackPressed();
            return;
        }
        if (isUpLoad()) {
            super.onBackPressed();
            return;
        }
        ExitDialog.getExitDialog("是否放弃此次批改？").setExitListener(new ExitDialog.ExitListener() {
            @Override
            public void onExit(boolean exitState) {
                if (exitState) {
                    HomeworkCorrectingActivity.super.onBackPressed();
                }
            }
        }).show(getSupportFragmentManager(), "dialog");
    }

    /**
     * 设置选项（手滑、打对号、打错号、书写文字、删除’）
     *
     * @param v
     * @param pen
     * @param selectType
     * @param editMode
     * @param isNoScroll
     */
    private void initSetViewSelect(View v, IDoodlePen pen, SelectType selectType, boolean editMode, boolean isNoScroll) {
        if (!setSelectedItemState(false)) {
            return;
        }
        if (mDoodleView == null || mTouchGestureListener == null || mViewPager == null || previousPage == null || nextPage == null)
            return;
        float size = 4 * mDoodleView.getUnitSize();
        mDoodleView.setShape(DoodleShape.HAND_WRITE);
        mDoodleView.setColor(new DoodleColor(Color.RED));
        mDoodleView.setZoomerScale((float) 2.5);
        mDoodleView.setSize(size);
        mDoodleView.setEditMode(editMode);
        this.selectType = selectType;
        if (pen != null) {
            mDoodleView.setPen(pen);
        }
        mTouchGestureListener.setSupportScaleItem(false);
        setViewState(v);
        mViewPager.setNoScroll(isNoScroll);
        previousPage.setVisibility(homeworkCorrectInfos.size() >= 2 && currentPosition > 0 && DoodlePen.BRUSH == pen ? View.VISIBLE : View.GONE);
        nextPage.setVisibility(homeworkCorrectInfos.size() >= 2 && currentPosition + 1 < homeworkCorrectInfos.size() && DoodlePen.BRUSH == pen ? View.VISIBLE : View.GONE);
    }

    /**
     * 将涂鸦后图片保存到本地(计数参数)
     */
    private int savePosition = 0;

    /**
     * 将涂鸦后图片保存到本地
     */
    private void toSave() {
        HomeworkCorrectingFragment f = getFragment(getSupportFragmentManager(), savePosition);
        DoodleView view = f.getContainerView();
        f.setListener(new HomeworkCorrectingFragment.SaveListener() {
            @Override
            public void onSaveSucceed() {
                statisticsSave();
            }

            @Override
            public void onFailure() {
                statisticsSave();
            }
        });
        view.save();
    }

    /**
     * 保存涂鸦图片统计
     */
    private void statisticsSave() {
        if (homeworkCorrectInfos == null) return;
        savePosition += 1;
        if (savePosition < homeworkCorrectInfos.size()) {
            toSave();
        } else {
            savePosition = 0;
            dismissProgressDialog();
            skipWorkPaper();
        }
    }

    /**
     * 跳转到作业点评界面
     */
    private void skipWorkPaper() {
        if (homeworkCorrectInfos == null) return;
        List<CorrectInfo> list = new ArrayList<>();
        for (HomeworkCorrectInfo info : homeworkCorrectInfos) {
            CorrectInfo correctInfo = new CorrectInfo();
            correctInfo.imMsgId = info.imMsgId;
            correctInfo.originalUrl = info.compressUrl;
            correctInfo.scrawlPath = info.scrawlPath;
            correctInfo.sessionId = info.sessionId;
            correctInfo.studentAccId = info.studentAccId;
            correctInfo.filename = info.filename;
            for (List<String> errer : info.errors.values()) {
                correctInfo.erreList.add(errer);
            }
            list.add(correctInfo);
        }
        Intent intent = new Intent();
        intent.setClass(this, WorkPaperActivity.class);
        intent.putExtra(WorkPaperActivity.KEY_IMAGE_INFO_LIST, (Serializable) list);
        intent.putExtra("tag",tag);
        startActivityForResult(intent, GlobalConstant.REQUEST_CODE_WORK_PAPER_ACTIVITY);
    }

    /**
     * 设置选项view状态
     *
     * @param view
     */
    public void setViewState(View view) {
        ViewGroup parentView = (ViewGroup) view.getParent();
        for (int i = 0; i < parentView.getChildCount(); i++) {
            View childView = parentView.getChildAt(i);
            childView.setSelected(childView == view);
        }
    }

    /**
     * 获取选中状态
     *
     * @return
     */
    @Override
    public SelectType getSelectType() {
        return selectType;
    }

    /**
     * 添加贴图
     *
     * @param doodleView
     * @param listener
     * @param doodleBitmap
     * @param x
     * @param y
     */
    @Override
    public void createDoodleBitmap(DoodleView doodleView, DoodleOnTouchGestureListener listener, final DoodleBitmap doodleBitmap, final float x, final float y) {
        this.mDoodleView = doodleView;
        this.mTouchGestureListener = listener;
        if (selectType == SelectType.ERROR) {
            getWordsNames();
        }
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), selectType == SelectType.ERROR ? R.drawable.cuo : R.drawable.dui_green);
        if (doodleBitmap == null) {
            int bitmapWidth = bitmap.getWidth();
            float scale;
            if (selectType == SelectType.ERROR) {
                float width = (float) DensityUtil.dp2px(30);
                scale = width / bitmapWidth;
            } else {
                float width = (float) DensityUtil.dp2px(55);
                scale = width / bitmapWidth;
            }
            IDoodleSelectableItem item = new MyDoodleBitmap(mDoodleView, bitmap, bitmap.getHeight(), x, y, selectType);
            item.setScale(scale);
            mDoodleView.addItem(item);
            if (selectType == SelectType.ERROR) {
                wrongNumberItems.get(currentPosition).add(item);
            }
//            mTouchGestureListener.setSelectedItem(item);
        } else {
            doodleBitmap.setBitmap(bitmap);
        }
        mDoodleView.refresh();
    }

    /**
     * 添加文字
     *
     * @param doodleView
     * @param listener
     * @param doodleText
     * @param x
     * @param y
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    public void createDoodleText(DoodleView doodleView, DoodleOnTouchGestureListener listener, final DoodleStoreText doodleText, final float x, final float y) {
        this.mDoodleView = doodleView;
        this.mTouchGestureListener = listener;
        if (isFinishing() || isDestroyed()) {
            return;
        }
        DialogController.showInputTextDialog(this, doodleText == null ? null : doodleText.getText(), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = (v.getTag() + "").trim();
                if (TextUtils.isEmpty(text)) {
                    return;
                }
                if (doodleText == null) {
                    IDoodleSelectableItem item = new DoodleStoreText(mDoodleView, text, mDoodleView.getSize(), mDoodleView.getColor().copy(), x, y);
                    item.setSize(DensityUtil.dp2px(14));
                    item.setScale(1);
                    mDoodleView.addItem(item);
                    mTouchGestureListener.setSupportScaleItem(true);
                    mTouchGestureListener.setSelectedItem(item);
                } else {
                    doodleText.setText(text);
                }
                mDoodleView.refresh();
            }
        }, null);
    }

    @Override
    public void setSelectedItemState() {
        setSelectedItemState(false);
    }

    /**
     * 设置清屏按钮状态
     */
    @Override
    public void setClearGreenViewState() {

        if (mDoodleView != null) {
            List<IDoodleItem> allItem = mDoodleView.getAllItem();
            cls.setVisibility(allItem != null && allItem.size() > 0 ? View.VISIBLE : View.GONE);
        } else {
            cls.setVisibility(View.GONE);
        }
    }

    /**
     * 同步状态
     */
    @Override
    public void synchronousState() {
        switch (selectType) {
            case TEXT:
                onClick(findViewById(R.id.voice));
                break;
            case ERROR:
                onClick(findViewById(R.id.wrongNumber));
                break;
            case DELETE:
                onClick(findViewById(R.id.delete));
                break;
            case CORRECT:
                onClick(findViewById(R.id.checkNumber));
                break;
            case REDACT:
                onClick(findViewById(R.id.painting));
                break;
        }
    }

    /**
     * 获取错误选项dialog参数
     */
    private void getWordsNames() {
        if (errerTypeInfos != null) {
            showDialog();
            return;
        }
        showProgressDialog("数据初始化...");
        CreateRequestEntity.getWebService().getWordsNameBySessionId(sessionId).enqueue(new Callback<BaseResult<ArrayList<String>>>() {
            @Override
            public void onResponse(Call<BaseResult<ArrayList<String>>> call, Response<BaseResult<ArrayList<String>>> response) {
                dismissProgressDialog();
                if (ResultVerifier.isSucceed(response)) {
                    errerTypeInfos = response.body().data;
                    showDialog();
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<ArrayList<String>>> call, Throwable t) {
                dismissProgressDialog();
                ResultVerifier.systerErrers(t);
            }
        });
    }

    /**
     * 错误贴图时显示dialog
     */
    private void showDialog() {
        if (errerTypeInfos == null) return;
        HomeworkErrorsFragment dialog = HomeworkErrorsFragment.getInstance(errerTypeInfos, accountId, sessionId);
        dialog.setHomeworkErrorsDialogListener(this);
        dialog.show(getSupportFragmentManager(), "homeworkErrorsFragment");
    }

    /**
     * 判断准备工作是否就绪
     *
     * @return
     */
    public boolean isDrawReady() {
        if (homeworkCorrectInfos == null) return false;
        for (int i = 0; i < homeworkCorrectInfos.size(); i++) {
            HomeworkCorrectingFragment f = getFragment(getSupportFragmentManager(), i);
            if (f != null) {
                if (!f.isDownLoadImageSucceed() || !f.isCreateDoodleView() || !f.isCreateGestureListener()) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 获取未涂鸦界面数组
     *
     * @return
     */
    private List<Integer> getNoScrawlPosition() {
        List<Integer> items = new ArrayList<>();
        if (homeworkCorrectInfos == null) return items;
        for (int i = 0; i < homeworkCorrectInfos.size(); i++) {
            HomeworkCorrectingFragment f = getFragment(getSupportFragmentManager(), i);
            if (f != null) {
                if (!f.isDownLoadImageSucceed() || !f.isCreateDoodleView() || !f.isCreateGestureListener() || !f.isScrawl()) {
                    items.add(i + 1);
                }
            }
        }
        return items;
    }

    /**
     * 获取fragment
     *
     * @param manager
     * @param position
     * @return
     */
    private HomeworkCorrectingFragment getFragment(FragmentManager manager, int position) {
        if (homeworkCorrectInfos == null) return null;
        HomeworkCorrectingFragment fragment = (HomeworkCorrectingFragment) manager.findFragmentByTag("android:switcher:" + mViewPager.getId() + ":" + position);
        return fragment == null ? HomeworkCorrectingFragment.getInstance(homeworkCorrectInfos.get(position)) : fragment;
    }

    /**
     * viewPager切换时初始化界面状态
     *
     * @param position
     */
    @SuppressLint("SetTextI18n")
    private void initSwitcherFragment(int position) {
        Log.e("initSwitcherFragment", "initSwitcherFragment=" + position);
        HomeworkCorrectingFragment f = getFragment(getSupportFragmentManager(), position);
        if (f != null) {
            if (f.isCreateDoodleView() && f.isDownLoadImageSucceed() && f.isCreateGestureListener()) {
                synchronousState();
                setClearGreenViewState();
            } else {
                f.reLoadBitmap();
                cls.setVisibility(View.GONE);
            }
        }
        if (homeworkCorrectInfos != null) {
            switchImage.setVisibility(homeworkCorrectInfos.get(position).isOriginalImage ? View.GONE :
                    (TextUtils.isEmpty(homeworkCorrectInfos.get(position).originalUrl) ? View.GONE : View.VISIBLE));
            pagerNumber.setText((position + 1) + "/" + homeworkCorrectInfos.size());
            findViewById(R.id.save).setVisibility(homeworkCorrectInfos.size() == position + 1 ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        currentPosition = position;
        initSwitcherFragment(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        if (state == ViewPager.SCROLL_STATE_IDLE) {
            HomeworkCorrectingFragment f = getFragment(getSupportFragmentManager(), currentPosition);
            if (f != null) {
                f.resumeLoadBitmap();
            }
        } else if (state == ViewPager.SCROLL_STATE_DRAGGING) {
            if (mTouchGestureListener != null) {
                mTouchGestureListener.setSelectedItem(null);
            }
            HomeworkCorrectingFragment f = getFragment(getSupportFragmentManager(), currentPosition);
            if (f != null) {
                f.stopLoadBitmap();
            }
        }
    }

    @Override
    protected void onDestroy() {
        mTouchGestureListener = null;
        mDoodleView = null;
        if (mViewPager != null) {
            mViewPager.removeAllViews();
            mViewPager = null;
        }
        super.onDestroy();
    }

    /**
     * 打错号，dialog点击取消时回调
     */
    @Override
    public void onDialogCancle() {
        if (wrongNumberItems != null && wrongNumberItems.size() > currentPosition && mDoodleView != null) {
            List<IDoodleItem> wrongNumberItem = wrongNumberItems.get(currentPosition);
            mDoodleView.removeItem(wrongNumberItem.get(wrongNumberItem.size() - 1));
            setClearGreenViewState();
        }
    }

    /**
     * 打错号，dialog点击确定时回调
     */
    @Override
    public void onDialogAffirm(List<String> selectTags) {
        if (wrongNumberItems != null && wrongNumberItems.size() > currentPosition && homeworkCorrectInfos != null
                && homeworkCorrectInfos.size() > currentPosition) {
            List<IDoodleItem> wrongNumberItem = wrongNumberItems.get(currentPosition);
            HomeworkCorrectInfo info = homeworkCorrectInfos.get(currentPosition);
            IDoodleItem wrongItem = wrongNumberItem.get(wrongNumberItem.size() - 1);
            info.setErrors(wrongItem, selectTags);
            Rect bound = ((DoodleSelectableItemBase) wrongItem).getBounds();
            PointF location = wrongItem.getLocation();
            float y = location.y + bound.height();
            for (String tag : selectTags) {
                y += DensityUtil.dp2px(selectTags.indexOf(tag) != 0 ? 15 : 8);
                MyDoodleText item = new MyDoodleText(mDoodleView, tag, DensityUtil.dp2px(10), new DoodleColor(Color.BLUE).copy(), wrongItem.getPivotX(), y, selectType);
                item.setErrorBitmap(wrongItem);
                mDoodleView.addItem(item);
            }
            setClearGreenViewState();
        }
    }

    /**
     * 将当前涂鸦设置为选中或未选中
     *
     * @param selected
     */
    private boolean setSelectedItemState(boolean selected) {
        HomeworkCorrectingFragment f = getFragment(getSupportFragmentManager(), currentPosition);
        if (f != null) {
            mDoodleView = f.getContainerView();
            mTouchGestureListener = f.onDoodleOnTouchGesture();
        }
        if (mTouchGestureListener != null) {
            IDoodleSelectableItem selectedItem = mTouchGestureListener.getSelectedItem();
            if (selectedItem != null) {
                selectedItem.setSelected(selected);
            }
        }
        return mTouchGestureListener != null && mDoodleView != null;
    }

    /**
     * 获取图片显示宽度区域
     *
     * @return
     */
    @Override
    public int getMySelfDisplayAreaWidth() {
        if (imageAreaWidth != 0) {
            return imageAreaWidth;
        }
        imageAreaWidth = ScreenUtil.getScreenWidth(this);
        return imageAreaWidth;
    }

    /**
     * 获取图片显示高度区域
     *
     * @return
     */
    @Override
    public int getMySelfDisplayAreaHeight() {
        if (imageAreaHeight != 0) {
            return imageAreaHeight;
        }
        imageAreaHeight = ScreenUtil.getScreenHeight(this) - DensityUtil.dp2px(98);
        return imageAreaHeight;
    }

    /**
     * 当前作业是否涂鸦(涂鸦界面<=总界面)
     *
     * @return
     */
    private boolean taskisDauber() {
        if (homeworkCorrectInfos == null) return false;
        for (int i = 0; i < homeworkCorrectInfos.size(); i++) {
            HomeworkCorrectingFragment f = getFragment(getSupportFragmentManager(), i);
            if (f != null) {
                if (f.isScrawl()) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 是否上传到服务器器
     *
     * @return
     */
    public boolean isUpLoad() {
        if (homeworkCorrectInfos == null) return false;
        for (HomeworkCorrectInfo info : homeworkCorrectInfos) {
            if (!info.isUpload) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case GlobalConstant.REQUEST_CODE_WORK_PAPER_ACTIVITY:
                    setResult(Activity.RESULT_OK, data);
                    finish();
                    break;
            }
        }
    }
}
